﻿using System;
using System.Web;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using com.dz.ht.common;



namespace com.dz.ht.components.book.site_3
{
    public class CollectBookManager : IBookObject
    {
        //搜索地址
        const string c_search_url = "http://www.shouda8.com/Ebook/Index.aspx?searchkey={0}&searchclass=1";

        /// <summary>
        /// 章节列表页面
        /// </summary>
        const string c_chapter_url = "http://www.xiaoshuoyd.com/4/{0}.html";

        //站点编码
        Encoding m_site_encoding = Encoding.GetEncoding("gb2312");

        const string c_reg_book = "<li[^<>]*?class=[\'\"]?storelistbt3b[\'\"]?>\\s*?<a[^<>]*?hrefs*=s*[\'\"]*([^\"\']*\\d+\\.html)[\'\"]*[^<>]*?>(.*?)</a>\\s*?<a.*?>.*?</a>";
        const int c_book_list_link_index = 1;
        const int c_book_list_name_index = 2;

        const string c_reg_book_intro="<li[^<>]*?class=[\'\"]?a2[\'\"]?>\\s*?<h1[^<>]*?class=[\'\"]?h1title[\'\"]?>\\s*?<a[^<>]*?hrefs*=s*[\'\"]*([^\"\']*\\d+)\\.html[\'\"]*[^<>]*?>(.*?)</a>\\s*?</h1>.*?<span>作者：(.*?)</li>\\s*?<li[^<>]*?class=[\'\"]?a3[\'\"]?>\\s*?总字数：(\\d+)\\s*?总点击：(\\d+)\\s*?总推荐：(\\d+)\\s*?作品类别：(.*?)\\s*?更新时间.*?<img[^<>]*?srcs*=s*[\'\"]*([^\"\']*)[\'\"]*[^<>]*?>.*?<li[^<>]*?class=[\'\"]?a2[^<>]*?id=[^<>]*?articledesc[^<>]*?>(.*?)</li>";
        const int c_book_intro_chapter_list_index=1;
        const int c_book_intro_book_name_index=2;
        const int c_book_intro_author_name_index=3;
        const int c_book_intro_words_count_index = 4;
        const int c_book_intro_click_count_index = 5;
        const int c_book_intro_collect_count_index = 6;
        const int c_book_intro_subcategory_name_index=7;
        const int c_book_intro_icon_index=8;
        const int c_book_intro_book_description_index = 9;

        //书名在正则中的索引
        const int c_book_name_index = 1;
        //章节列表url在正则中的索引
        const int c_book_id_index = 2;
        //章节列表导航在正则中的索引
        const int c_menu_index = 3;
        const string c_menu_txt = "在线阅读";

        //匹配分卷正则
        const string c_volume_reg = "<div[^<>]*?class=[\'\"]?chapter_list_chapter_title[\'\"]?[^<>]*?>.*?<b>(.*?)</b>.*?</div>";
        //整洁正则
        const string c_chapter_reg = "<div[^<>]*?class=[\'\"]?chapter_list_chapter[\'\"]?><a[^<>]*?hrefs*=s*[\'\"]*([^\"\']*\\d+)\\.html[\'\"]*[^<>]*?title=[^<>]*?(\\d{4}-[\\d{2}|\\d{1}]+-[\\d{2}|\\d{1}]+\\s*?[\\d{2}|\\d{1}]+:[\\d{2}|\\d{1}]+)[^<>]*?>(.*?)</a>";
        //更新时间
        const int c_update_time_index =2;
        //章节id
        const int c_chapter_id_index = 1;
        //章节名称
        const int c_chapter_name_index = 3;

        //搜索列表正则
        const string c_search_reg = "<li>.*?<H3><A.*?>(.*?)</A></H3>.*?<div[^<>]*?class=[\'\"]?button[\'\"]?>.*?<a[^<>]*?hrefs*=s*[\'\"s]?[^\"]*\\/(\\d+)[^\"]*[\'\"]?[^<>]*?>(.*?)</a>";
        /// <summary>
        /// 章节内容地址
        /// </summary>
        const string c_chapter_content_url = "http://www.xiaoshuoyd.com/yd/{0}/{1}.html";
        const string c_chapter_content_reg = "<script.*?>outputtxt\\([\'\"]?(.*?)[\'\"]?\\)\\s*?;\\s*?<\\/script>";

         /// <summary>
        /// 获取首页所有的书籍
        /// </summary>
        /// <param name="i_book_default_url"></param>
        /// <returns></returns>
        public Dictionary<string, string> CollectDefaultBookList(string i_book_default_url)
        {
            return null;
        }

        /// <summary>
        /// 收集某个地址的所有小说详情地址
        /// </summary>
        /// <param name="i_book_list_url">http://www.shouda8.com/Book/ShowBookList.aspx?tclassid=0&nclassid=0&page=2&orderbyid=0</param>
        /// <returns>小说地址及小说名称</returns>
        public Dictionary<string, string> CollectBookList(string i_book_list_url)
        {

            Dictionary<string, string> t_dic = null;
            try
            {
                string t_html = NetSiteCatchManager.ReadUrl(i_book_list_url, m_site_encoding);
                if (!string.IsNullOrEmpty(t_html))
                {
                    MatchCollection t_ma = Regex.Matches(t_html, c_reg_book, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    if (t_ma != null && t_ma.Count > 0)
                    {
                        t_dic = new Dictionary<string, string>();
                        foreach (Match t_mc in t_ma)
                        {
                            if (t_mc.Groups.Count > c_book_list_link_index)
                            {
                                if (!t_dic.ContainsKey(string.Format("http://www.xiaoshuoyd.com{0}", t_mc.Groups[c_book_list_link_index].Value.ToString())))
                                {
                                    t_dic.Add(string.Format("http://www.xiaoshuoyd.com{0}", t_mc.Groups[c_book_list_link_index].Value.ToString()), t_mc.Groups[c_book_list_name_index].Value.ToString());
                                }

                            }
                        }
                    }
                }
                return t_dic;
            }
            catch (Exception ex)
            {
                LogHelper.Error("收集小说列表地址失败" + ex.ToString());
            }

            return t_dic;
        }

                 /// <summary>
        /// 收集某本小说详细信息
        /// </summary>
        /// <param name="i_book_url"></param>
        /// <returns></returns>
        public BookInfo CollectBookItem(string i_book_url)
        {
            BookInfo t_book = null;
            try
            {
                string t_html = NetSiteCatchManager.ReadUrl(i_book_url, m_site_encoding);

                if (!string.IsNullOrEmpty(t_html))
                {

                    Match t_mc = Regex.Match(t_html, c_reg_book_intro, RegexOptions.IgnoreCase | RegexOptions.Compiled);

                    if (t_mc != null && t_mc.Groups.Count >= c_book_intro_icon_index)
                    {
                        t_book = new BookInfo();
                        t_book.BookUrl = i_book_url;
                        t_book.ChapterUrl ="http://www.xiaoshuoyd.com"+ t_mc.Groups[c_book_intro_chapter_list_index].Value.ToString() + "/";
                        t_book.BookName = t_mc.Groups[c_book_intro_book_name_index].Value.ToString();
                        t_book.AuthorName = t_mc.Groups[c_book_intro_author_name_index].Value.ToString();
                        t_book.BookSubCagegoryName = t_mc.Groups[c_book_intro_subcategory_name_index].Value.ToString();
                        int t_click = 0;
                        int t_collect = 0;
                        if (!int.TryParse(t_mc.Groups[c_book_intro_click_count_index].Value.ToString(), out t_click))
                            t_click = 0;
                        if (!int.TryParse(t_mc.Groups[c_book_intro_collect_count_index].Value.ToString(), out t_collect))
                            t_collect = 0;
                        t_book.Click = t_click;
                        t_book.Collect = t_collect;
                        t_book.BookStatus = "连载";

                        t_book.Description = t_mc.Groups[c_book_intro_book_description_index].Value.ToString();
                        //去掉lebel标签
                        t_book.Description = Regex.Replace(t_book.Description, "<.*?label.*?>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled); 
                        //div标签
                        t_book.Description = Regex.Replace(t_book.Description, "<.*?div.*?>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                        //超链接
                        t_book.Description = Regex.Replace(t_book.Description, "<a.*?>.*?</a>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                        t_book.ImageUrl =t_mc.Groups[c_book_intro_icon_index].Value.ToString();

                        if (!string.IsNullOrEmpty(t_book.ImageUrl) && t_book.ImageUrl.IndexOf("noimg")<0)
                            t_book.IsExistsImage = true;

                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("收集小说详情失败" + ex.ToString());
            }

            return t_book;
        }

            /// <summary>
        /// 收集某本书的所有章节
        /// </summary>
        /// <param name="i_chapter_list_url"></param>
        /// <returns></returns>
        public List<BookChapterInfo> CollectChapterList(string i_chapter_list_url)
        {
            List<BookChapterInfo> t_chapter_list = new List<BookChapterInfo>();
            long t_site_book_id=0;
             Match t_mc=Regex.Match(i_chapter_list_url,"\\/(\\d+)\\/",RegexOptions.IgnoreCase|RegexOptions.Compiled);
            if(t_mc!=null)
            {
                if(!long.TryParse(t_mc.Groups[1].Value.ToString(),out t_site_book_id))
                    t_site_book_id=0;
            }
            string t_html = string.Empty;
            MatchCollection t_ma = null;
            string t_volume_name = string.Empty;
            string t_sub_html = string.Empty;
            try
            {
                t_html = NetSiteCatchManager.ReadUrl(i_chapter_list_url, m_site_encoding);
                t_ma = Regex.Matches(t_html, c_volume_reg, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                if (t_ma != null && t_ma.Count > 0)
                {
                    for (int t_index = 0; t_index < t_ma.Count - 1; t_index++)
                    {
                        t_volume_name = t_ma[t_index].Groups[1].Value.ToString();
                        t_sub_html = t_html.Substring(t_ma[t_index].Groups[1].Index, t_ma[t_index + 1].Groups[1].Index - t_ma[t_index].Groups[1].Index);
                        t_chapter_list.AddRange(ParseChapter(t_volume_name, t_sub_html, t_site_book_id));
                        
                    }

                    t_volume_name = t_ma[t_ma.Count - 1].Groups[1].Value.ToString();
                    t_sub_html = t_html.Substring(t_ma[t_ma.Count - 1].Index);

                    t_chapter_list.AddRange(ParseChapter(t_volume_name, t_sub_html, t_site_book_id));

                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取章节列表失败" + ex.ToString());
            }

            return t_chapter_list;
        }

        /// <summary>
        /// 解析章节信息
        /// </summary>
        /// <param name="i_volume_name"></param>
        /// <param name="i_text"></param>
        /// <param name="i_site_book_id"></param>
        /// <returns></returns>
        private List<BookChapterInfo> ParseChapter(string i_volume_name, string i_text, long i_site_book_id)
        {
            if (string.IsNullOrEmpty(i_text))
                return new List<BookChapterInfo>();

            if (string.IsNullOrEmpty(i_volume_name))
            {
                i_volume_name = "残卷";
            }

            List<BookChapterInfo> t_chapter_list = new List<BookChapterInfo>();
            MatchCollection t_ma = Regex.Matches(i_text, c_chapter_reg, RegexOptions.IgnoreCase | RegexOptions.Compiled);
            DateTime t_update_time = DateTime.Now;

            string t_site_chapter_id = string.Empty;
            string t_chapter_name = string.Empty;
            bool t_is_vip = false;
   
            if (!string.IsNullOrEmpty(i_volume_name) && i_volume_name.ToLower().IndexOf("vip") > -1)
            {
                t_is_vip = true;
            }
            if (t_ma != null)
            {

                foreach (Match t_mc in t_ma)
                {
                    if (t_mc.Groups.Count >= c_chapter_name_index)
                    {
                        BookChapterInfo t_chapter = new BookChapterInfo();
                        t_chapter.VolumeName = i_volume_name;
                        if (!DateTime.TryParse(t_mc.Groups[c_update_time_index].Value.ToString(), out t_update_time))
                            t_update_time = DateTime.Now;
                        t_chapter.UpdateTime = t_update_time;

                        t_site_chapter_id = t_mc.Groups[c_chapter_id_index].Value.ToString();
                        t_chapter_name = t_mc.Groups[c_chapter_name_index].Value.ToString();

                        t_chapter.ChapterName = t_chapter_name;

                        t_chapter.Comfrom = string.Format(c_chapter_content_url, i_site_book_id, t_site_chapter_id);
                        t_chapter.IsVip = t_is_vip;
                        t_chapter_list.Add(t_chapter);
                    }
                }
            }

            return t_chapter_list;
        }

            /// <summary>
        /// 收集章节内容
        /// </summary>
        /// <param name="i_chapter_content_url"></param>
        /// <returns></returns>
        public string CollectChapterContent(string i_chapter_content_url)
        {
             string t_chapter_content=string.Empty;
             string t_content_url = string.Empty;
            try
            {
                string t_html = NetSiteCatchManager.ReadUrl(i_chapter_content_url, m_site_encoding);
                if (!string.IsNullOrEmpty(t_html))
                {
                    Match t_mc = Regex.Match(t_html, c_chapter_content_reg, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    if (t_mc != null && t_mc.Groups.Count > 0)
                    {
                        t_content_url = t_mc.Groups[1].Value.ToString();
             
                        t_content_url = string.Format("http://r.wl01.com:88/novel{0}", t_content_url);
                        t_chapter_content = NetSiteCatchManager.ReadUrl(t_content_url, m_site_encoding);
                        if (!string.IsNullOrEmpty(t_chapter_content))
                        {
                            string t_reg_content = "document.writeIn\\('(.*?)\'\\)";
                            Match t_mc_content = Regex.Match(t_chapter_content, t_reg_content, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                            if (t_mc_content != null && t_mc_content.Groups.Count > 0)
                            {
                                t_chapter_content = t_mc_content.Groups[1].Value.ToString();
                            }
                        }
                        //100字以上才算章节
                        if (!string.IsNullOrEmpty(t_chapter_content) && t_chapter_content.Length > 100)
                        {
                            t_chapter_content = NetSiteCatchManager.ReplaceContent(t_chapter_content);
                            t_chapter_content = string.Format("document.write('{0}');", t_chapter_content);
                           
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取章节内容失败" + ex.ToString());
            }

            return t_chapter_content;
        }

      

     
    }
}
